package com.leoman.plz_p.utils;

import android.content.Context;
import android.graphics.Paint;
import android.text.Html;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.com.corelib.utils.ToastMgr;


public class ValidationUtil {

    public static boolean validatePhone(String phone) {
        Pattern p = Pattern
                .compile("^(0|86|17951)?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$");
        Matcher matcher = p.matcher(phone);
        return matcher.matches();
    }

    public static boolean validatePhoneWithToast(String phone) {
        if (TextUtils.isEmpty(phone)) {
            ToastMgr.show("请输入手机号码");
            return false;
        } else {
            if (ValidationUtil.validatePhone(phone)) {
                return true;
            } else {
                ToastMgr.show("请输入正确的手机号码");
                return false;
            }
        }

    }

    private boolean validateCodeWithToast(String code) {
        if (TextUtils.isEmpty(code)) {
            ToastMgr.show("请输入验证码");
            return false;
        } else {
            if (code.length() != 6) {
                ToastMgr.show("验证码为6位");
                return false;
            } else {
                return true;
            }
        }
    }

    private boolean validatePasswordWithToast(String password) {
        if (TextUtils.isEmpty(password)) {
            ToastMgr.show("请输入密码");
            return false;
        } else {
            if (password.length() < 6) {
                ToastMgr.show("密码过于简单");
                return false;
            } else {
                return true;
            }
        }
    }

    public static boolean containsEmoji(String source) {
        int len = source.length();
        boolean isEmoji = false;
        for (int i = 0; i < len; i++) {
            char hs = source.charAt(i);
            if (0xd800 <= hs && hs <= 0xdbff) {
                if (source.length() > 1) {
                    char ls = source.charAt(i+1);
                    int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                    if (0x1d000 <= uc && uc <= 0x1f77f) {
                        return true;
                    }
                }
            } else {
                // non surrogate
                if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                    return true;
                } else if (0x2B05 <= hs && hs <= 0x2b07) {
                    return true;
                } else if (0x2934 <= hs && hs <= 0x2935) {
                    return true;
                } else if (0x3297 <= hs && hs <= 0x3299) {
                    return true;
                } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                    return true;
                }
                if (!isEmoji && source.length() > 1 && i < source.length() -1) {
                    char ls = source.charAt(i+1);
                    if (ls == 0x20e3) {
                        return true;
                    }
                }
            }
        }
        return  isEmoji;
    }

    /**
     * 是否是空string
     *
     * @param string
     * @return
     */
    public static boolean isNullString(String string) {
        return string == null || string.equals("") || string.equals("null") || string.length() == 0;
    }

    /**
     * 获取n位小数
     *
     * @param n
     * @param data
     * @return
     */
    public static String getDecimal(int n, String data) {
        return String.format("%." + n + "f", Double.parseDouble(data));
    }

    /**
     * 获取n位随机数
     *
     * @param n
     * @return
     */
    public static String getRandomNumber(int n) {
        String string = "";
        while (string.length() < n) {
            string += (int) (Math.random() * 10);
        }
        return string;
    }

    /**
     * 获取html格式
     *
     * @param parameter
     * @return
     */
    public static Spanned getHtml(Object... parameter) {
        return Html.fromHtml("<font color=\"" + parameter[0] + "\">" + parameter[1] + "</font><font color=\"" + parameter[2] + "\">" + parameter[3] + "</font>");
    }

    /**
     * 获取html格式
     *
     * @param imageGetter
     * @param parameter
     * @return
     */
    public static Spanned getHtml(Html.ImageGetter imageGetter, Object... parameter) {
        return Html.fromHtml("<font color=\"" + parameter[0] + "\">" + parameter[1] + "</font><font color=\"" + parameter[2] + "\">" + parameter[3] + "</font>"
                + "<img src=\"" + parameter[4] + "\"/>", imageGetter, null);
    }

    /**
     * 从assets获取数据
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getDataFromAssets(Context context, String fileName) {
        String result;
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            int byteCount;
            while ((byteCount = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, byteCount);
            }
            outputStream.flush();
            inputStream.close();
            outputStream.close();
            result = new String(outputStream.toByteArray(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            result = null;
        }
        return result;
    }

    /**
     * 设置现金的输入方式与输入限制
     *
     * @param editText EditText
     */
    public static void setCrashInput(EditText editText) {
        editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        editText.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(".") && dest.toString().length() == 0) {
                    return "0.";
                }
                if (dest.toString().contains(".")) {
                    int index = dest.toString().indexOf(".");
                    int mlength = dest.toString().substring(index).length();
                    if (mlength == 3) {
                        return "";
                    }
                }
                return null;
            }
        }});
    }

    /**
     * 设置下横线
     */
    public static void setUnderline(TextView textView) {
        textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        textView.getPaint().setAntiAlias(true);
    }

    /**
     * 设置删除线
     */
    public static void setMiddlelien(TextView textView) {
        textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        textView.getPaint().setAntiAlias(true);
    }


    /**
     * 时间转换
     * @param type yyyy.MM.dd HH:mm
     */
    public static String formatTime(String createTime, String type) {
        long msgCreateTime = Long.parseLong(createTime);
        DateFormat format = new SimpleDateFormat(type);
        return format.format(new Date(msgCreateTime));
    }

    public static boolean isRightIDCard(String text) {

        String Ai = "";

        // 18位身份证前17位位数字，如果是15位的身份证则所有号码都为数字
        if (text.length() == 18) {
            Ai = text.substring(0, 17);
        } else if (text.length() == 15) {
            Ai = text.substring(0, 14);
        }
        if (isNumeric(Ai) == false) {

            return false;
        }
        return true;
    }

    /**
     * 判断字符串是否为数字
     * @param strnum
     * @return
     */
    private static boolean isNumeric(String strnum) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(strnum);
        if (isNum.matches()) {
            return true;
        } else {
            return false;
        }
    }

    private static String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
}
